<?php


namespace app\home\service;


use app\common\model\GameRecords;
use app\common\model\Luzhu;
use app\common\model\UserModel;
use app\job\UserSettleTaskJob;
use app\job\UserTigerSettleTaskJob;
use think\facade\Db;
use think\facade\Queue;

class CardDragonTigerService
{
    /**
     * 龙虎牌面结算
     * 1 计算完成 修改用户总赢。修改用户金额
     * 2 游戏结果计算
     * 3 洗码费计算(如果出现台面作废，洗码费就不写入，所有必须是正常开牌的才把经费通过定时任务发放)
     * 4 代理计算
     * 5 开牌以后 开牌以后的下注信息 转移 插入到 资金记录表 redis  TransferBetService 执行
     * @param $post
     */
    public function open_game($post): string
    {
        $luzhuModel = new Luzhu();
        //插入开牌信息
        $save = $luzhuModel->save($post);
        //开牌的时候 把开牌信息存入到redis...用作桌面 牌显示
        redis()->set('table_id_' . $post['table_id'] . '_' . $post['game_type'], $post['result_pai'], 5);
        if (!$save) show([], 0, '开牌失败');
        $post['luzhu_id'] = $luzhuModel->id;
        $queue = Queue::later(1, UserTigerSettleTaskJob::class, $post);
        if ($queue == false) {
            show([], 0, 'dismiss job queue went wrong');
        }

        return show([]);
    }

    //用户结算以及写入订单信息,单独写方便后面检查
    public function user_settlement($luzhu_id, $post): bool
    {
        $oddsModel = new GameRecords();
        //1 触发该牌桌 所有购买的用户 是否中奖。中奖后修改当前下单信息
        //得到本次下注用户订单列表.只查询前一个小时的。不需要查询太久了的
        $win_the_prize = $oddsModel
            ->whereTime('created_at', date("Y-m-d H:i:s", strtotime("-1 hour")))
            ->where([
                'table_id' => $post['table_id'], 'game_type' => $post['game_type'],
                'xue_number' => $post['xue_number'], 'pu_number' => $post['pu_number'],
                'close_status' => 1,
            ])
            ->select()
            ->toArray();
        //对本次下单用户计算获得金额

        if (empty($win_the_prize)) return true;

        //保存当前修改下注信息数据
        $data = [];
        //保存修改用户获取金额
        $user = [];
        $TransferBetService = new TransferBetService();
        //获得本地本次开牌结果
        $card = new OpenDragonTigerService();
        $pai_result = $card->runs(json_decode($post['result_pai'], true));
        foreach ($win_the_prize as $key => $value) {
            //资金激励存入redis
            $TransferBetService->redis_insert_bet_money_log(json_encode($value));
            //查询当前用户是否中奖   返回 false 是没中奖  true是中奖
            $data[$key]['detail'] = $value['detail'] .
                '-购买：' . $card->user_pai_chinese($value['result']) .
                ',开：' . $card->pai_chinese($pai_result) .
                '||本次结果记录' . json_encode($pai_result);
            $user_win_or_not = $card->user_win_or_not(intval($value['result']), $pai_result);
            $data[$key]['close_status'] = 2;//2 牌面已结算
            $data[$key]['win_amt'] = $value['bet_amt'] * -1;//会员总赢默认为 为下注金额
            $data[$key]['id'] = $value['id'];
            $data[$key]['lu_zhu_id'] = $luzhu_id;
            //判断该用户是否 赢了。 true 赢   false 输  用户购买 结果和开奖结果是否一样
            if ($user_win_or_not == true) {
                //会员下注金额*比例
                $money = $value['game_peilv'] * $value['bet_amt'];
                $data[$key]['win_amt'] = $money;//计算会员总赢  赔率 * 下注金额
                $data[$key]['delta_amt'] = $money + $value['bet_amt'];//计算会员变化金额.盈利+下注本金
                $user[$key]['money_balance'] = $money + $value['bet_amt']; //用户需要增加的金额 盈利+下注本金
                $user[$key]['id'] = $value['user_id'];
            }
        }

        //组装用户资金数据
        $user_data = [];
        if (!empty($user)) {
            foreach ($user as $v) {
                //如果存在说明用户购买了多条
                if (array_key_exists($v['id'], $user_data)) {
                    $user_data[$v['id']]['money_balance'] += $v['money_balance'];
                } else {
                    $user_data[$v['id']] = $v;
                }
            }
        }
        // 启动事务
        Db::startTrans();
        try {
            //写入用户余额
            if (!empty($user_data)) {
                foreach ($user_data as $key => $value) {
                    (new UserModel())->where('id', $value['id'])->inc('money_balance', $value['money_balance'])->update();
                }
            }
            !empty($data) && $oddsModel->saveAll($data);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        return true;
    }
}

